package com.wangzha.api;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;
import com.wangzha.business.service.*;
import com.wangzha.common.base.BaseController;
import com.wangzha.common.cache.CacheKey;
import com.wangzha.common.enums.TaskStatusEnum;
import com.wangzha.common.model.*;
import com.wangzha.common.oss.OSSProvider;
import com.wangzha.common.response.R;
import com.wangzha.portal.core.service.SysUserService;
import com.wangzha.pub.login.service.LoginService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;


@Path("/api")
public class APIController extends BaseController {

    private static final Logger LOG = Logger.getLogger(APIController.class);

    @Inject
    LoginService loginService;

    @Inject
    SysUserService sysUserService;

    @Inject
    DeviceService deviceService;

    @Inject
    ApkVersionService apkVersionService;

    @Inject
    OSSProvider ossProvider;

    @Inject
    UserUploadFileService uploadFileService;

    @Inject
    TaskService taskService;

    @Inject
    DeviceActiveCodeService deviceActiveCodeService;

    /**
     * 鉴权
     */
    public void verify() {
        DeviceActiveCode deviceActiveCode = deviceActiveCodeService.findByActiveCode(getPara("code"));
        if (deviceActiveCode == null) {
            renderJson(R.fail("授权失败"));
        } else {
            if (deviceActiveCode.getStatus().intValue() == 0) {
                deviceActiveCode.setStatus(1);
                deviceActiveCode.update();
                renderJson(R.success("授权成功"));
            } else {
                renderJson(R.success("该激活码已授权"));
            }
        }
    }

    public void getTask() {
        if(StringUtils.isBlank(getPara("code"))) {
            renderJson(R.data(null));
        } else {
            List taskList = taskService.findByActiveCodeAndState(getPara("code"), TaskStatusEnum.READY_TO_RUN.getState());
            Redis.use().setex(String.format(CacheKey.DEVICE_HEARTBEAT, getPara("code")), 60,"online");
            if (CollectionUtils.isEmpty(taskList)) {
                renderJson(R.data(null));
            } else {
                renderJson(R.data(taskList.get(0)));
            }
        }
    }

    public void updateTask() {
        Device device = deviceService.findByActivationCode(getPara("code"));
        if (device == null) {
            renderJson(R.fail("设备不存在"));
        } else {
            boolean flag = taskService.updateStateById(getParaToLong("id"), getParaToInt("status"));
            if (flag) {
                renderJson(R.success("更新状态成功"));
            } else {
                renderJson(R.fail("更新状态失败"));
            }
        }
    }

    private static String geneToken() {
        return RandomStringUtils.randomAlphanumeric(18);
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param d1 时间参数 1 格式：1990-01-01 12:00:00
     * @param d2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static String getDistanceTime(Date d1, Date d2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long time1 = d1.getTime();
        long time2 = d2.getTime();
        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        return day + "天" + hour + "小时" + min + "分";
    }


    public void updateVersion() {
        ApkVersion apkVersion = apkVersionService.getLastApkVersion();
        Map dataMap = null;
        if (apkVersion == null) {
            renderJson(R.success("没有最新版本"));
        } else {
            dataMap = new HashMap(3);
            dataMap.put("version", apkVersion.getVersion());
            String reqUrl = "https://dyver.oss-cn-beijing.aliyuncs.com/wz/update/";
            List<String> list = JSON.parseArray(apkVersion.getFileUrl(), String.class);
            Map<Object, Object> urlMap = new HashMap<>(10);
            if (list != null && list.size() > 0) {
                for (String name : list) {
                    if (StringUtils.isNotBlank(name)) {
                        // 包更新
                        if (NumberUtils.toInt(apkVersion.getType() + "") == 0) {
                            urlMap.put("apkUrl", name);
                        } else {
                            urlMap.put(name, reqUrl + name);
                        }
                    }
                }
            }
            dataMap.put("url", urlMap);
            dataMap.put("type", apkVersion.getType());
            dataMap.put("content", apkVersion.getContent());
        }
        renderJson(R.data(dataMap));
    }


    public void updateVersion2() {
        ApkVersion apkVersion = apkVersionService.getLastApkVersion();
        Map dataMap = null;
        if (apkVersion == null) {
            renderJson(R.success("没有最新版本"));
        } else {
            dataMap = new HashMap(3);
            dataMap.put("version", apkVersion.getVersion());
            String reqUrl = "https://dyver.oss-cn-beijing.aliyuncs.com/wz/update/";
            List<String> list = JSON.parseArray(apkVersion.getFileUrl(), String.class);
            Map<Object, Object> urlMap = new HashMap<>(10);
            if (list != null && list.size() > 0) {
                for (String name : list) {
                    if (StringUtils.isNotBlank(name)) {
                        // 包更新
                        if (NumberUtils.toInt(apkVersion.getType() + "") == 0) {
                            urlMap.put("apkUrl", name);
                        } else {
                            urlMap.put(name, reqUrl + name);
                        }
                    }
                }
            }
            dataMap.put("url", urlMap);
            dataMap.put("type", apkVersion.getType());
            dataMap.put("content", apkVersion.getContent());
        }
        renderJson(R.data(dataMap));
    }

    public void uploadFile() {
        if (StringUtils.isBlank(getPara("identifier"))) {
            renderJson(R.fail("上传文件失败"));
            return;
        }

        Device device = deviceService.findByActivationCode(getPara("code"));
        if (device == null) {
            renderJson(R.fail("上传文件失败"));
            return;
        }

        if (uploadFileService.findByPk("identifier", getPara("identifier")) != null) {
            renderJson(R.fail("上传文件失败,此文件已上传"));
            return;
        }

        UploadFile up = getFile();
        if (up != null) {
            //String fileKey = UUID.randomUUID().toString().replaceAll("-", "");
            String url = ossProvider.putObject(up.getFile(), getPara("identifier"));
            File file = new File(up.getUploadPath() + "/" + up.getOriginalFileName());
            file.delete();
            if (StringUtils.isBlank(url)) {
                renderJson(R.fail("上传文件失败"));
                return;
            } else {
                UserUploadFile userUploadFile = new UserUploadFile();
                userUploadFile.setUserCode(device.getUserCode());
                userUploadFile.setName(up.getFileName());
                userUploadFile.setUrl(url);
                userUploadFile.setActiveCode(getPara("code"));
                userUploadFile.setType(getParaToInt("file_type"));
                userUploadFile.setIdentifier(getPara("identifier"));
                userUploadFile.setRunTime(getParaToLong("run_time"));
                userUploadFile.setAppName(getPara("app_name"));
                userUploadFile.setAppVersion(getPara("app_version"));
                userUploadFile.setCreateTime(new Date());
                if (userUploadFile.save()) {
                    renderJson(R.success("上传文件成功"));
                    return;
                } else {
                    renderJson(R.fail("上传文件失败"));
                    return;
                }
            }
        }
    }

    public void checkFileUnique() {
        if (StringUtils.isBlank(getPara("identifier"))) {
            renderJson(R.fail("检查文件唯一性失败"));
            return;
        }

        Device device = deviceService.findByActivationCode(getPara("code"));
        if (device == null) {
            renderJson(R.fail("检查文件唯一性失败"));
            return;
        }

        if (uploadFileService.findByPk("identifier", getPara("identifier")) != null) {
            renderJson(R.fail("此文件已上传"));
            return;
        }

        renderJson(R.success("此文件未上传"));
        return;
    }


    public static void main(String[] args) {

        System.out.println(URLDecoder.decode("%E6%8A%96%E9%9F%B3"));
    }
}
